package handler

import (
	"fig-doc/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
)

func ArtAdd(c *gin.Context) {
	Title := c.PostForm("Title")
	Content := c.PostForm("Content")
	Img := c.PostForm("Img")
	data := model.Article{
		Title:   Title,
		Content: Content,
		Img:     Img,
	}
	if Title == "" && len(Title) > 10 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "正文标题不可为空，并且长度10字以内",
		})
		return
	}
	if Content == "" && len(Title) > 50 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "正文标题不可为空，并且长度50字以内",
		})
		return
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func ArtList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var article []model.Article
	model.DB.Debug().Offset(offset).Limit(size).Find(&article)
	var count int64
	model.DB.Model(&model.Article{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  article,
		"count": count,
	})
	return
}

func ArtDetail(c *gin.Context) {
	id := c.Query("id")
	var article model.Article
	model.DB.Debug().Where("id=?", id).Find(&article)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": article,
	})
	return
}

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	log.Println(file.Filename)

	dst := "./file" + file.Filename
	err := c.SaveUploadedFile(file, dst)
	if err != nil {
		return
	}

	c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
}
